package org.ricks.net;

import org.ricks.net.kit.DataCodecKit;
import org.ricks.net.buffer.WriteBuffer;
import org.ricks.net.transport.UdpAioSession;
import org.ricks.net.transport.UdpChannel;
import java.net.SocketAddress;
import java.nio.ByteBuffer;

/**
 * @author chenwei
 * KCP 默认开启了快速，数据写回就 flush
 * @date 2022/10/1218:45
 */
public class KcpSeesion extends UdpAioSession  {

    private long tsUpdate = -1;
    private long lastCheckTime = Long.MIN_VALUE;

    //经过kcp处理过的数据包（原始数据来自send（bb）中的bb
    private Kcp kcp = new Kcp() {
        @Override
        public void out(ByteBuffer data) {
            if(!isInvalid()) writeBuffer().write(data);
        }
    };


    public KcpSeesion(UdpChannel udpChannel, SocketAddress remote, WriteBuffer writeBuffer) {
        super(udpChannel, remote, writeBuffer);
    }


    public Kcp getKcp() {
        return kcp;
    }

    @Override
    public void write(Object obj) {
        int code = 0;
        try {
            code = kcp.send(DataCodecKit.encode(obj));
        } catch (Exception e) {
            code = -9;
        }
        if(code == 0) kcp.update(System.currentTimeMillis()); else close();
    }
}



